/**
 * 封装本地存
 * 1，可以存储任意类型数据
 * 2，可以设置存储的过期时间
 */

export default {
  setItem (key, value, options = {}) {
    const val = {
      data: value,
      options: {
        ...options,
        maxAge: options.maxAge ? (options.maxAge + (+new Date())) : 'all',
      }
    }

    localStorage.setItem(key, JSON.stringify(val))
  },
  getItem (key) {
    let value = localStorage.getItem(key)
    console.log(key, value)
    if (value) {
      value = JSON.parse(value)
      if (value.options.maxAge === 'all') {
        return value.data
      } else {
        const date = +new Date()
        console.log(date, value.options.maxAge, value)
        if (value.options.maxAge > date) {
          console.log('对呀')
          return value.data
        } else {
          localStorage.removeItem(key)
          return null
        }
      }
    } else {
      return null
    }
  },
  removeItem (key) {
    localStorage.removeItem(key)
  }
}
